package org.tinygroup.springwithtemplate3.impl;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.tinygroup.context.Context;
import org.tinygroup.context.impl.ContextImpl;
import org.tinygroup.template.TemplateContext;

public class SpringTemplateContext extends ContextImpl implements TemplateContext{

	private HttpServletRequest request;
	
	public SpringTemplateContext(Map<String, ?> model,
			HttpServletRequest request) {
		super(model);
		this.request = request;
	}
	
	public SpringTemplateContext(HttpServletRequest request) {
		super();
		this.request = request;
	}
	
	public boolean exist(String name) {
        if (super.exist(name)) {
            return true;
        }
        if(request!= null){
           if(request.getParameter(name)!= null){
        	  return true;
           }else if(request.getAttribute(name)!= null){
        	  return true;
           }
        }
        Context parentContext = getParent();
        if (parentContext != null) {
            return parentContext.exist(name);
        }
        return false;
    }
	
	public <T> T get(String name) {
        T result = super.get(name);
        if (result != null) {
            return result;
        }
        if(request!= null){
        	Object  r = request.getParameter(name);
        	if(r != null){
        	  return (T) r;
        	}
        	r = request.getAttribute(name);
        	if(r != null){
          	  return (T) r;
          	}
        }
        Context parentContext = getParent();
        if (parentContext != null) {
            return (T) parentContext.get(name);
        }
        return null;
    }
	
}
